<?php

if( !defined("IN_ELCIUS") ) exit;


class ExternalContent{
	
	private static $initalized = false;
	
	private static $link;
	private static $connected;
	
	private static $totalTimeout;
	
	private static $timeout = 8;
	
	public static $Data; // public data, write-only, untrustworthy scum
	
	public static function Initialize(){
		self::$totalTimeout = time()+25;
		self::$initalized = true;
		self::$Data = array(
			'Connected' => false,
		);
	}
	
	
	public static function Fetch( $url, $validationStr, $expireTime = 86400 ){
		
		if( self::$initalized ){
			
			$cache = self::CheckCache( $url );
			if( $cache ){
				if( $cache['Timestamp']+$expireTime >= time() ){ // cache fresh enough to use
					return $cache['Data'];
				}
			}
			
			if( time()+self::$timeout > self::$totalTimeout ){ // total timeout expired, not allowed to fetch anymore
				echo "[ExternalContent::Fetch]: Total Timeout Limit Reached.</br>"; // TEMP
				return $cache['Data'];
			}
			
			
			echo "[ExternalContent::Fetch]: Fetching \"".$url."\" ... "; // TEMP
			
			$data = @file_get_contents(
				$url,
				false,
				stream_context_create(
					array(
						'http' => array('timeout' => self::$timeout)
					)
				)
			);
			
			// TODO: error supression, make sure url is safe, possibly whitelist domains.
			// TODO: replace with pass-through, make sure page is actually what it is expected to be before updating cache.
			
			if( empty($data) or !strstr( $data, $validationStr ) ){
				if( $data === false and empty( $cache['Data'] ) ){
					echo '<b>Request Failed!</b>, Cache Empty.</br>'; // TEMP
					// TODO: stop trying to fetch invalid urls
				}
				else{
					echo '<b>Validation Failed!</b>, Using Cache.</br>'; // TEMP
					$data = $cache['Data'];
				}
			}
			else{
				echo '<b>Validated</b>, Updating Cache.</br>'; // TEMP
				self::UpdateCache( $url, $data );
			}
			return $data;
		}
		return false;
	}
	
	// cache stuff
	public static function Connect(){
		global $Settings;
		
		self::$connected = false;
		self:$Data['Connected'] = false;
		
		if( !self::$link ) {
			self::$link = new pdo(
				'mysql:host='.$Settings['MySQL_host'].';dbname='.$Settings['ExternalContentCache_database'],
				$Settings['MySQL_username'],
				$Settings['MySQL_password']
			);
			if ( self::$link ){
				self::$connected = true;
				self::$Data['Connected'] = true;
			}
		}
		
		return self::$connected;
	}
	
	private static function CheckCache( $url ){
		if( self::$connected or self::Connect() ){
			// TODO: partitions
			$result = self::$link->prepare( 'SELECT * FROM `cachedcontent` WHERE `ID` = ? LIMIT 1' );
			$result->execute( array( self::GetID($url) ) );
			if( $result ){
				return $result->Fetch( PDO::FETCH_ASSOC );
			}
		}
		return false;
	}
	
	private static function UpdateCache( $url, $data ){
		if( self::$connected or self::Connect() ){
			// TODO: partitions
			$result = self::$link->prepare( 'REPLACE INTO `cachedcontent` (`ID`,`Data`,`Timestamp`) VALUES ( ?, ?, '.time().' );' )->execute( array( self::GetID($url), $data ) );
			return $result;
		}
		return false;
	}
	
	private static function GetID( $url ){
		return md5($url);
	}
	
}

?>